package com.atguigu.juc.completableFuture;

import java.util.concurrent.*;

/**
 * @author yfstart
 * @create 2022-06-13 19:39
 */
public class CompletableFutureUseDemo {
  public static void main(String[] args) throws ExecutionException, InterruptedException {
    // supplyAsyncExtracted();
    whenCompleteAsyncExtracted();
  }

  private static void whenCompleteAsyncExtracted() {
    ExecutorService threadPool = Executors.newFixedThreadPool(3);
    try {
      CompletableFuture<Integer> completableFuture =
          CompletableFuture.supplyAsync(
                  () -> {
                    System.out.println(Thread.currentThread().getName() + "\t ---come in");
                    int result = ThreadLocalRandom.current().nextInt(10);
                    try {
                      TimeUnit.MILLISECONDS.sleep(1000);
                    } catch (InterruptedException e) {
                      e.printStackTrace();
                    }
                    System.out.println("---一秒后出结果：" + result);
                    int j = 1 / 0;
                    return result;
                  },
                  threadPool)
              .whenCompleteAsync(
                  (r, e) -> {
                    if (e == null) {
                      System.out.println("----计算完成，更新系统updateValue：" + r);
                    }
                  })
              .exceptionally(
                  e -> {
                    System.out.println("异常情况：" + e.getCause() + "\t" + e.getMessage());
                    return 1024;
                  });
      System.out.println(Thread.currentThread().getName() + "\t ---线程先去忙其他任务");
      // 主线程不要立刻结束，否则CompletableFuture默认使用的线程池会立刻关闭:暂停3秒钟线程
      // try {TimeUnit.MILLISECONDS.sleep(3000);} catch (InterruptedException e)
      // {e.printStackTrace();}
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      threadPool.shutdown();
    }
  }

  private static void supplyAsyncExtracted() throws InterruptedException, ExecutionException {
    CompletableFuture<Integer> supplyAsync =
        CompletableFuture.supplyAsync(
            () -> {
              System.out.println(Thread.currentThread().getName() + "\t ---come in");
              int result = ThreadLocalRandom.current().nextInt(10);
              try {
                TimeUnit.MILLISECONDS.sleep(1000);
              } catch (InterruptedException e) {
                e.printStackTrace();
              }
              System.out.println("---一秒后出结果：" + result);
              return result;
            });
    System.out.println(Thread.currentThread().getName() + "\t ---线程先去忙其他任务");

    System.out.println("supplyAsync.get() = " + supplyAsync.get());
  }
}
